package com.screwdriver.jso.client;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArrayInteger;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by IntelliJ IDEA. User: jan kowalski Date: 09.08.11 Time: 21:31 To
 * change this template use File | Settings | File Templates.
 */
public class JSONCompatibleConverter {

	public static JsArrayInteger fromIntArray(int[] array) {
		JsArrayInteger result = JavaScriptObject.createArray().cast();
		for (int i : array) {
			result.push(i);
		}
		return result;
	}

	public static int[] toIntArray(JavaScriptObject javaScriptObject) {
		JsArrayInteger intArray = javaScriptObject.cast();
		int[] result = new int[intArray.length()];
		for (int i = 0; i < intArray.length(); i++) {
			result[i] = intArray.get(i);
		}
		return result;
	}

	public static JsArrayInteger fromIntCollection(Collection<Integer> array) {
		JsArrayInteger result = JavaScriptObject.createArray().cast();
		for (int i : array) {
			result.push(i);
		}
		return result;
	}

	public static Collection<Integer> toIntCollection(JavaScriptObject javaScriptObject) {
		JsArrayInteger intArray = javaScriptObject.cast();
		return toGivenCollection(intArray, new ArrayList<Integer>(intArray.length()));
	}
	
	public static List<Integer> toIntList(JavaScriptObject javaScriptObject) {
		JsArrayInteger intArray = javaScriptObject.cast();
		return toGivenCollection(intArray, new ArrayList<Integer>(intArray.length()));
	}
	
	public static Set<Integer> toIntSet(JavaScriptObject javaScriptObject) {
		JsArrayInteger intArray = javaScriptObject.cast();
		return toGivenCollection(intArray, new HashSet<Integer>());
	}

	private static <T extends Collection<Integer>> T toGivenCollection(JsArrayInteger intArray, T result) {
		for (int i = 0; i < intArray.length(); i++) {
			result.add(intArray.get(i));
		}
		return result;
	}

}
